<template>
  <view class="live-container">
    <!-- 头部 -->
    <live-navabar
      :title="details.ysf_name"
      @other-btn="onOtherBtn"
      :initially-id="initiallyId"
      :box-id="currentBox.box_id"
      v-if="graduallyShow.top"
    ></live-navabar>
    <!-- 主体 商品列表 -->
    <view class="compartmentals">
      <!-- 主体 -->
      <view class="good-main">
        <live-good-main
          :details="details"
          v-if="graduallyShow.goodsMain"
          id="maingood"
        ></live-good-main>
      </view>
      <!-- 商品列表 -->
      <view class="goods-group">
        <live-goods-group
          id="goodsgroup"
          :total="boxTotal"
          :current-box="currentBox"
          :probability="probabilitySwitch"
          @open="changeBoxListMod(true)"
          @change="switchBox"
          @look="lookDetailsMod"
          v-if="graduallyShow.goodsList"
        ></live-goods-group>

        <view class="silde-img">
          <image class="br" mode="widthFix" :src="br" />
          <image class="br" mode="widthFix" :src="br" />
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-group">
      <view class="left-explain">
        <live-switch-btn
          :currentBox="currentBox"
          :total="boxTotal"
          @next="onNext"
          @previous="onPrevious"
          @open="changeBoxListMod(true)"
        ></live-switch-btn>
      </view>
      <view class="right-lottery">
        <live-lottery-group
          @lottery="onLottery"
          :details="extractable"
        ></live-lottery-group>
      </view>
    </view>
    <!-- 展开按钮 -->
    <view class="unfold-btn">
      <unfold-btn
        :active-id="initiallyId"
        @unfold="onUnfold"
        :bottom="'--bottom: 70vh;'"
      ></unfold-btn>
    </view>
    <!-- 开奖动画  -->
    <view class="result-live" :hidden="!lotteryResultOpen">
      <lottery-result
	  :isindex="aainde"
        :show="lotteryResultOpen"
        :animation-data="animationImg"
        :result-list="lotteryResultList"
        @again="onAgain"
        @close="onLotteryResultClose"
      ></lottery-result>
    </view>
    <!-- 开奖记录 -->
    <view class="history-live" v-if="lotteryHistoryOpen">
      <lottery-history
        :initially-id="initiallyId"
        :box-id="currentBox.box_id"
        @change-history-mod="changeHistoryMod"
      ></lottery-history>
    </view>
    <!-- 规则 -->
    <rules
      :details="explain"
      v-if="explainOpen"
      @change-rules-mod="changeRulesMod"
    ></rules>
    <!-- 箱子列表 -->
    <box-list
      v-if="boxListModuleStauts"
      :initially-id="initiallyId"
      :current-box="currentBox"
      :total="boxTotal"
      :rows="boxRows"
      @change-box-list-mod="changeBoxListMod"
      @select="selectBox"
    ></box-list>
    <!-- 分享 -->
    <shopro-share v-model="showShare" posterType="user"></shopro-share>
    <!-- 支付 -->
    <live-pay-model
      :history="payHistory"
      @change-pay-mod="changePayMod"
      @result="onDrawResults"
      @payed="onPayed"
      v-if="showTrade"
      activity-type="yfs"
      :protocol="initiallyId"
      :details="payDetails"
    ></live-pay-model>
  </view>
</template>
<script>
import br from '../img/silter-0.png';
import BoxList from '../components/live-box-list.vue';
import LiveNavabar from '../components/live-navbar.vue';
import LiveGoodMain from '../components/live-good-main.vue';

import { EXTRACTABLEE } from '../portrait/portait_config';
import share from '@/shopro/share';
import { mapActions, mapMutations, mapGetters } from 'vuex';
import LiveGoodsGroup from '../components/live-goods-group.vue';
import LiveLotteryGroup from '../components/live-lottery-group.vue';
import LiveSwitchBtn from '../components/live-switch-btn.vue';

import UnfoldBtn from '../components/unfold-btn.vue';
import LotteryResult from '../components/live-lottery-result.vue';
import LotteryHistory from '../components/live-lottery-history.vue';
import Rules from '../components/live-rules.vue';

export default {
  // 建议 创建每个组件时 都添加name属性 标识组件名称
  name: '',
  components: {
    LiveNavabar,
    LiveGoodMain,
    LiveGoodsGroup,
    LiveLotteryGroup,
    LiveSwitchBtn,
    UnfoldBtn,
    LotteryResult,
    LotteryHistory,
    Rules,
    BoxList,
  },
  data() {
    return {
      br,
      // 全局视图展示开关
      graduallyShow: {
        // 顶部展示
        top: false,
        // 商品列表展示
        goodsList: false,
        // 商品主体展示
        goodsMain: false,
        // 额外按钮展示
        borderButtonDis: false,
        // 抽奖按钮区展示
        lotteryShow: false,
      },
		aainde:false,
      initiallyId: '',

      //当前查看商品id
      productId: '',

      //当前商品信息
      details: {},
      // 当前箱子
      currentBox: {
        // 箱子id
        box_id: 0,
        // 当前箱子位置
        index: 0,
        //箱子内 商品列表
        box_goods: {
          list: [],
          //商品总数
          total: 0,
        },
        // 商品库存
        box_num: {
          // 总库存
          total: 0,
          // 当前箱子内 剩余商品数量
          surplus: 0,
        },
        //箱子顺序
        box_sort: {
          // 当前总箱子数
          count: 0,
          // 当前箱子数
          sort: 0,
        },
        // 可抽取 按钮
        price: {
          single: '',
          five: '',
          ten: '',
          all: '',
        },
      },
      // 箱子数量
      boxTotal: 0,
      //箱子区间数
      boxRows: 4,
      /**
       * 箱子列表
       * [
       * [],
       * [],
       * [],
       * [],
       * ]
       *
       */
      boxList: [],
      //结果列表
      lotteryResultList: [],
      // 抽取方式
      extractable: EXTRACTABLEE,
      rollNum: '',
      //说明
      explain: '',

      // 动画加载
      animationImg: {
        start: {
          cdn:
            this.$IMG_URL +
            '/uploads/20230427/7a4cb0b6cd4b96accdf19ded4e0ddf40.gif',
          status: false,
          count: 0,
          url: '',
        },
        light: {
          cdn:
            this.$IMG_URL +
            '/uploads/20230427/807f1102f46064a246a130eb7562e316.png',
          status: false,
          count: 0,
          url: '',
        },
      },
      // 交易信息
      payDetails: {},
      payHistory: {
        type: '',
      },

      // 音效开启关闭
      soundOpen: true,
      // 中奖纪录显示隐藏
      winningRecordOpen: false,
      // 规则展示隐藏
      rulesOpen: false,
      // 支付展示
      paymentOpen: false,
      // 指示点
      indicatorDots: false,
      // 箱子列表弹窗显示
      boxListModuleStauts: false,
      // 抽奖 结果展示
      lotteryResultOpen: false,
      // 开奖纪录展示
      lotteryHistoryOpen: false,
      // 规则显示隐藏
      explainOpen: false,
      //分享 显示隐藏
      showShare: false,
      // 交易弹窗
      showTrade: false,
      // 查看款式详情
      productDetails: false,
    };
  },
  // 计算属性 适配者模式
  computed: {
    ...mapGetters(['allSkip']),
    // 概率显示隐藏
    probabilitySwitch() {
      let type = this.details?.probability_switch || '0';
      return type == '1' ? true : false;
    },
    // 遮罩打开
    modMaskOpen() {
      return this.boxListModuleStauts;
    },
  },
  // 数据监听
  watch: {},
  /**
   * 生命周期 类似 发布订阅者模式
   */
  //监听页面初始化，其参数同 onLoad 参数 触发时机早于 onLoad 百度小程序
  //onInit() {},
  /** 监听页面加载
   * 其参数为上个页面传递的数据，
   * 参数类型为 Object（用于页面传参）
   */
  onLoad(e = {}) {
    let { title, id, box_id } = e;
    this.initiallyId = this.$Route.query?.id || id || '';
    this.currentBox.box_id = box_id || 0;
    this.globalGraduallyShow();
	
	this.innerAudioContext = uni.createInnerAudioContext();
	this.innerAudioContext.src = 'https://file.aitewan.com/uploads/20241028/3d1128fd31eec653fba18a00e67c40ff.mp3';
	this.innerAudioContext.loop = true
  },
  // 监听页面显示。页面每次出现在屏幕上都触发 包括从下级页面点返回露出当前页面
  onShow() {
	  this.innerAudioContext.play()
	  this.$refs.unfoldbtn.sound = true
  },
  // 监听页面初次渲染完成 注意如果渲染速度快，会在页面进入动画完成前触发
  onReady() {},
  // 监听页面隐藏
  onHide() {
	  this.innerAudioContext.pause()
  },
  // 监听页面卸载
  onUnload() {
	  this.innerAudioContext.stop()
  },
  methods: {
    ...mapActions(['changeAllSkip']),
    ...mapMutations(['CartOnshow']),

    //继续抽奖 继续欧气
    onAgain() {
      this.lotteryResultOpen = false;
      // this.showTrade = true;
      this.getBoxTotal()
        .then(() => {
          return this.getBoxDetails({
            action: 'selected',
            box_id: this.currentBox.box_id,
          });
        })
        .then(() => {
          return this.getDetails();
        })
        .then(() => {
          this.onLottery({
            data: {
              id: this.rollNum,
            },
          });
        })
        .catch(() => {});
    },

    // 关闭 抽奖结果
    onLotteryResultClose() {
      this.lotteryResultOpen = false;
      this.getBoxTotal()
        .then(() => {
          return this.getBoxDetails({
            action: 'selected',
            box_id: this.currentBox.box_id,
          });
        })
        .then(() => {
          return this.getDetails();
        })
        .then(() => {})
        .catch(() => {});
    },

    // 渐序展示视图
    globalGraduallyShow() {
      // 执行列表
      const eventList = this.orderOfExecution();
      // 组件渲染延迟 函数
      const fn = (_ev = () => {}, delay = 400) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            _ev();
            resolve(true);
          }, delay);
        });
      };
      // 视图列表
      const views = Object.keys(this.graduallyShow);
      const len = views.length;

      return new Promise(async (resolve, reject) => {
        // 按顺序 依次执行
        for (let i = 0; i < len; i++) {
          const item = views[i];
          // 延迟800ms
          let t = 60;
          if (eventList[item]) {
            // 请求
            try {
              let result = await eventList[item]();
              // 请求异步 耗时 耗时大于60ms直接渲染 小于60ms异步差值 渲染
              t = result.time > 60 ? 0 : 60 - result.time;
            } catch (error) {
              t = error.time > 60 ? 0 : 60 - error.time;
            }
          }
          // 执行 延迟函数
          const timeout = await fn(() => {
            // 渲染
            this.$set(this.graduallyShow, item, true);
            // // 获取商品主体高度
            // if (item == 'goodsMain') {
            //   this.getGroupMain();
            // }
            if (i == len - 1) {
              resolve();
            }
          }, t);
        }
      });
    },
    // 对应的执行顺序请求数据
    orderOfExecution() {
      /***
       * 箱子请求操控
       * 初次进来
       * 1 获取 一番赏 信息
       * 2 获取箱子总数
       * 3 获取箱子列表
       * 4 获取当前箱子详情
       */

      return {
        top: null,
        lotteryShow: null,
        borderButtonDis: null,
        // 获取 商品列表
        goodsList: () => {
          const tim0 = new Date().getTime();
          return new Promise((resolve, reject) => {
            this.getBoxTotal()
              .then(() => {
                return this.getBoxDetails({
                  box_id: this.currentBox.box_id,
                });
              })
              .then(() => {
                const tim1 = new Date().getTime();
                resolve({ time: tim1 - tim0 });
              })
              .catch(() => {
                const tim1 = new Date().getTime();
                reject({ time: tim1 - tim0 });
              });
          });
        },
        // 商品主体
        goodsMain: () => {
          const tim0 = new Date().getTime();
          return new Promise((resolve, reject) => {
            this.getDetails()
              .then(() => {
                const tim1 = new Date().getTime();
                resolve({ time: tim1 - tim0 });
              })
              .catch(() => {
                const tim1 = new Date().getTime();
                reject({ time: tim1 - tim0 });
              });
          });
        },
      };
    },

    //监听右上角自定义按钮
    onOtherBtn(ev) {
      switch (ev.name) {
        case 'look':
          this.getRules().then(() => {
            this.explainOpen = true;
          });

          break;
        case 'share':
          share.setShareInfo({
            title: this.details.ysf_name,
            desc: '',
            image: this.details.cover_image,
            params: {
              page: 5,
              pageId: this.initiallyId,
            },
          });

          this.showShare = true;
          break;
        case 'live':
          break;
        case 'up':
          let content = '';
          if (this.allSkip) {
            content = '是否需要开启抽奖动画';
          } else {
            content = '是否需要跳过抽奖动画';
          }
          uni.showModal({
            title: '抽奖动画',
            content,
            showCancel: true,
            cancelText: '取消',
            confirmText: '确定',
            success: (result) => {
              if (result.confirm) {
                this.changeAllSkip(!this.allSkip);
              }
            },
            fail: () => {},
            complete: () => {},
          });

          break;
      }
    },

    // 获取商品信息
    getDetails() {
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.yfsinfo',
          {
            id: this.initiallyId,
          },
          '加载中...'
        ).then((res) => {
          if (res.code === 1) {
            this.details = res.data;
            share.setShareInfo({
              title: this.details.ysf_name,
              desc: '',
              image: this.details.cover_image,
              params: {
                page: 5,
                pageId: this.initiallyId,
              },
            });

            //获取 箱子总数
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    // 获取 箱子总数
    getBoxTotal() {
      return new Promise((resolve, reject) => {
        this.$http('v1.yfsboxstotal', {
          id: this.initiallyId,
        }).then((res) => {
          if (res.code === 1) {
            this.boxTotal = res.data || 1;
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    // 获取规则
    getRules() {
      return new Promise((resolve, reject) => {
        if (this.explain) {
          resolve();
          return;
        }
        this.$http(
          'v1.activitysDetails',
          {
            activity_id: this.initiallyId,
            type: 'yfs',
          },
          '加载中'
        ).then((res) => {
          if (res.code === 1) {
            this.explain = res.data.content;
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    // 监听点击抽奖
    onLottery(ev) {
		
		if(this.$store.state.shopro.sound){
			var aa = uni.createInnerAudioContext()
			aa.src = 'https://file.aitewan.com/uploads/20241028/2c5733fd71abc106a083b7a1df0fe626.mp3';
			aa.play()
		}
		this.aainde= !this.aainde
		
		
      let residual = this.currentBox?.box_num?.surplus;
      // let total  = this.currentBox?.box_num?.total
      if (residual == 0) {
        uni.showToast({
          title: '该箱已被抽空，去其他箱盒看看吧',
          icon: 'none',
          duration: 1500,
          mask: true,
        });
        return;
      }
      this.getBoxDetails({
        action: 'selected',
        box_id: this.currentBox.box_id,
      }).then((details) => {
        let num = this.currentBox?.box_num?.surplus;
        if (num && num > 0) {
          this.rollNum = ev.data.id;
          let params = {
            activity_type: 'yfs',
            activity_id: this.initiallyId,
            roll_num: this.rollNum,
            box_id: this.currentBox.box_id,
          };
          this.$http('v1.createOrder', params, '正在创建').then((res) => {
            if (res.code === 1) {
              this.payDetails = {
                ...res.data,
              };
              this.showTrade = true;
            }
          });
        } else {
          uni.showToast({
            title: '该箱已被抽空',
            icon: 'none',
            duration: 1500,
            mask: true,
          });
        }
      });
    },
    // 关闭 交易弹窗
    changePayMod(e) {
      this.rollNum = '';
      this.showTrade = e;
      this.payDetails = {};
    },

    /**
     * @description 获取箱子列表
     * @param {Object} ev
     */
    getBoxList(ev = {}) {
      let { status = 'init', page = 1, rows = 1 } = ev;
      // 初始化
      if (status === 'init') {
      }
      return new Promise((resolve, reject) => {
        this.$http('v1.yfsboxs', {
          id: this.initiallyId,
          page,
          rows,
        }).then((res) => {
          if (res.code === 1) {
            this.boxList = res.data;
            resolve(res.data);
          } else {
            reject();
          }
        });
      });
    },

    // 获取箱子详情
    getBoxDetails(ev = {}) {
      let { status = 'init', action = 'selected', box_id = '0' } = ev;
      return new Promise((resolve, reject) => {
        this.$http(
          'v1.yfsBoxsAction',
          {
            id: this.initiallyId,
            box_id,
            action,
          },
          '加载中'
        ).then((res) => {
          if (res.code === 1) {
            this.currentBox.index = res.data?.box_sort?.sort;
            this.currentBox = Object.assign(this.currentBox, res.data);

            uni.$emit('live_yfs', {
              id: this.initiallyId,
              box_id: this.currentBox.box_id,
            });
            Object.keys(this.currentBox.price).forEach((item) => {
              const ele = this.currentBox.price[item];
              this.$set(this.extractable[item], 'price', ele);
            });
            resolve();
          } else {
            reject();
          }
        });
      });
    },

    // 选择箱子
    selectBox(ev) {
      this.getBoxDetails({
        action: 'selected',
        box_id: ev.item.box_id,
      })
        .then(() => {})
        .catch(() => {});
    },

    //切换箱子
    switchBox(e) {
      const fn = () => {
        return e.success();
      };
      switch (e.direction) {
        case 'next':
          this.getBoxDetails({
            action: 'next',
            box_id: this.currentBox.box_id,
          })
            .then(fn)
            .catch(fn);
          break;
        case 'previous':
          this.getBoxDetails({
            action: 'last',
            box_id: this.currentBox.box_id,
          })
            .then(fn)
            .catch(fn);
          break;

        default:
          this.getBoxDetails({
            action: 'next',
            box_id: this.currentBox.box_id,
          })
            .then(fn)
            .catch(fn);
          break;
      }
    },

    // 显示隐藏 商品详情
    changeDetailsMod(ev) {
      this.productId = '';
      this.productDetails = ev;
    },
    // 查看 商品详情
    lookDetailsMod(ev) {
      this.productId = ev;
      this.productDetails = true;
    },

    // 结果
    onDrawResults(ev) {
      this.lotteryResultOpen = true;
      this.showTrade = false;
      this.lotteryResultList = ev;
    },

    // 支付后的结果
    onPayed(ev) {
      this.payHistory = { type: ev.type };
      let param = {
        id: this.initiallyId,
        order_sn: ev.result.data.order_sn,
        roll_num: this.rollNum,
        box_id: this.currentBox.box_id,
      };
      // 进行获取奖品
      this.$http('v1.yfsRoll', param, '请稍等').then((res) => {
        if (res.code === 1) {
          this.onDrawResults(res.data);
          this.CartOnshow(true);
        }
      });
    },

    // 箱子列表展示隐藏
    changeBoxListMod(e) {
      this.boxListModuleStauts = e;
    },
    // 开奖记录展示隐藏
    changeHistoryMod(e) {
      this.lotteryHistoryOpen = e;
    },
    // 规则显示隐藏
    changeRulesMod(e) {
      this.explainOpen = e;
    },

    // 轮播图
    changeSwiper(e) {},
    // 监听组件自定义事件
    onModEvent() {},
    // 获取主商品区域范围
    getGroupMain() {
      setTimeout(() => {
        this.$nextTick(() => {
          const query = uni.createSelectorQuery().in(this);
          query
            .select('#maingood')
            .boundingClientRect((data) => {
              if (data.height) {
                this.groupHeight = {
                  style: `calc(100vh - ${data.height}px)`,
                  height: data.height,
                };
              }
            })
            .exec();
        });
      }, 400);
    },
    // 监听 扩展按钮 事件
    onUnfold(e) {
      switch (e.type) {
        //音效
        case 'noise':
		
		this.$store.commit('CHANGE_SOUND',e.status)
		if(e.status){
			this.innerAudioContext.play()
		}else{
			this.innerAudioContext.pause()
		}
		
          break;
        // 开奖记录
        case 'history':
          this.changeHistoryMod(e.status);
          break;
        // 盒柜
        case 'cabinet':
          break;
        // 刷新
        case 'refresh':
          uni.showLoading({
            title: '刷新中',
            mask: true,
          });
          this.globalGraduallyShow().then(() => {
            uni.hideLoading();
          });
          break;
      }
    },
    // 下一箱
    onNext() {
      // 触发
      uni.$emit('nextBox', true);
    },
    // 上一箱
    onPrevious() {
      uni.$emit('previousBox', true);
    },
  },
};
</script>
<style lang="scss" scoped>
.live-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  --br-width: 14rpx;

  --main-w: calc(100vh * 0.7173);
  // padding-bottom: 60rpx;
  &::before {
    position: fixed;
    top: 0;
    left: 0;
    content: '';
    width: 100%;
    height: 100%;
    background-image: linear-gradient(
        0deg,
        #660ab6 0px,
        #660ab6 2rpx,
        transparent 2rpx,
        transparent 100rpx
      ),
      linear-gradient(
        90deg,
        #660ab6 0px,
        #660ab6 2rpx,
        transparent 2rpx,
        transparent 100rpx
      );
    background-size: 13rpx 13rpx;
    opacity: 0.6;
    z-index: -1;
  }
  &::after {
    position: fixed;
    top: 0;
    left: 0;
    content: '';
    width: 100%;
    height: 100%;
    opacity: 1;
    z-index: -2;
    background: #4604a2;
  }
  .compartmentals {
    display: flex;
    justify-content: space-between;
    width: 100vw;
    min-height: 75vh;
    // height: 313px;
    height: 100%;
    padding-bottom: calc(100vh * 0.18);

    .good-main {
      flex-shrink: 0;
      width: var(--main-w);
      height: 100%;
    }
    .goods-group {
      position: relative;
      flex-shrink: 0;
      flex-grow: 1;
      padding-left: 10rpx;
      width: 402rpx;
      height: 100%;
      overflow: hidden;

      .silde-img {
        position: absolute;
        top: 0;
        right: 0;
        width: var(--br-width);
        display: flex;
        flex-direction: column;
        animation: slide-in-top var(--yfs-silde-time) linear 0s infinite
          alternate none;
      }
      .br {
        flex-shrink: 0;
        width: var(--br-width);
        // height: 850rpx;
        // -webkit-box-reflect: below;
      }
    }
  }
}
.bottom-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 20;
  width: 100vw;
  height: calc(100vh * 0.196);
  background-color: RGBA(224, 222, 247, 1);
  border-radius: 10rpx 10rpx 0rpx 0rpx;

  .left-explain {
    width: var(--main-w);
    height: 100%;
  }
  .right-lottery {
    position: relative;
    flex-shrink: 0;
    flex-grow: 1;
    padding-left: 10rpx;
    width: 402rpx;
    height: 100%;
  }
}
.unfold-btn {
  position: relative;
  z-index: 50;
  transform-origin: 100% 50%;
  transform: scale(0.5);
}
.history-live {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 100000;
  width: 350rpx;
  height: 96vh;
  // overflow: hidden;
  // background-color: #fff;
}
@keyframes slide-in-top {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-50%);
  }
}
</style>
